package com.example.vote.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.vote.bean.Result;
import com.example.vote.bean.TItem;
import com.example.vote.service.TItemServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 项目
 */
@RequestMapping("/item")
@RestController
@CrossOrigin
public class ItemController {

    @Autowired
    private TItemServiceImpl itemService;

//    @Autowired
//    WxMaService wxMaService;

    //    @RequestMapping(produces = {MediaType.IMAGE_JPEG_VALUE})
//    public void create(HttpServletResponse response) throws WxErrorException {
//        byte[] bytes = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes("1000",
//                "pages/vote/vote", false, "trial", 430, true, null, false);
//        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
//        try {
//            response.getOutputStream().write(bytes);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    @SaCheckLogin
    @RequestMapping("/list")
    public Result list() {
        List<TItem> list = itemService.list();
        return Result.success(list, "success");
    }

    /**
     * 创建投票
     *
     * @param item
     * @param files
     * @return
     * @throws IOException
     * @throws WxErrorException
     */
    @SaCheckLogin
    @PostMapping("/createVote")
    public Result createVote(TItem item, MultipartFile[] files) throws IOException, WxErrorException {
        Result result = itemService.createVote(item, files);
        return result;
    }

    /**
     * 查询当前用户创建的投票
     *
     * @param page
     * @param limit
     * @return
     */
    @SaCheckLogin
    @GetMapping("/page")
    public Result page(Integer page, Integer limit) {
        //todo:获取当前用户id
        String id = StpUtil.getLoginIdAsString();
        LambdaQueryWrapper<TItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TItem::getPhone, id);
        Page<TItem> pageInfo = itemService.page(Page.of(page, limit), wrapper);
        return Result.success(pageInfo, "success");
    }

    @SaCheckLogin
    @GetMapping("deleted")
    public Result deleted(String id) {
        boolean b = itemService.deletedItem(id);
        if (b) {
            return Result.success(null, "删除成功");
        }
        return Result.error("删除失败");
    }
}
